package 深拷贝对象;

import java.io.*;

public class 深拷贝对象
{

    // 1. Department类（需支持序列化）
    public static class Department implements Serializable {
        private String name;

        public Department(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Department{name='" + name + "'}";
        }
    }

    // 2. Employee类（实现Serializable以支持序列化）
    public static class Employee implements Serializable {
        private String name;
        private Department department;

        public Employee(String name, Department department) {
            this.name = name;
            this.department = department;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Department getDepartment() {
            return department;
        }

        public void setDepartment(Department department) {
            this.department = department;
        }

        @Override
        public String toString() {
            return "Employee{name='" + name + "', department=" + department + "}";
        }

        // 使用序列化实现深拷贝
        public Employee deepCopy() throws IOException, ClassNotFoundException {
            try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
                 ObjectOutputStream oos = new ObjectOutputStream(bos)) {
                oos.writeObject(this);

                try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
                     ObjectInputStream ois = new ObjectInputStream(bis)) {
                    return (Employee) ois.readObject();
                }
            }
        }
    }

    // 3. 主程序演示
    public static void main(String[] args) throws Exception {
        // 创建原始对象
        Department dept = new Department("IT");
        Employee original = new Employee("Alice", dept);

        // 深拷贝
        Employee copy = original.deepCopy();

        // 修改原始对象内容
        original.setName("Bob");
        original.getDepartment().setName("HR");

        // 输出验证深拷贝是否生效
        System.out.println("Original: " + original);
        System.out.println("Copy:     " + copy);

        // 验证对象引用是否不同
        System.out.println("\nDifferent object references:");
        System.out.println("original == copy: " + (original == copy));
        System.out.println("original.department == copy.department: " + 
                           (original.getDepartment() == copy.getDepartment()));
    }
}